import tools from "./tools.js";

export default class Tab {
  constructor(options) {
    options = options || { el: ".tab", currName: "current" };
    let oTab = document.querySelector(options.el),
      oPage = oTab.getElementsByClassName("page")[0];

    this.oNav = oTab.getElementsByClassName("nav")[0];
    this.oNavItems = this.oNav.getElementsByClassName("nav-item");
    this.oPageItems = oPage.getElementsByClassName("page-item");
    this.curIndex = 0;
    //配置项
    this.currName = options.currName;
  }

  init() {
    this.bindEvent();
  }
  bindEvent() {
    this.oNav.addEventListener("click", this.onNavClick.bind(this), false);
  }
  onNavClick(ev) {
    let tar = tools.getTarget(ev);
    let className = tar.className;

    if (className === "nav-item") {
      this.setCurrent(this.curIndex, "remove");
      this.curIndex = [].indexOf.call(this.oNavItems, tar);
      this.setCurrent(this.curIndex, "add");
    }
  }
  //切换current
  setCurrent(index, field) {
    switch (field) {
      case "add":
        this.oNavItems[index].classList.add(this.currName);
        this.oPageItems[index].classList.add(this.currName);
        break;
      case "remove":
        this.oNavItems[index].classList.remove(this.currName);
        this.oPageItems[index].classList.remove(this.currName);
        break;
      default:
        break;
    }
  }
}
